package com.auto.learning.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auto.learning.MainActivity;
import com.auto.learning.R;
import com.auto.learning.activity.TopBookListActivity;
import com.auto.learning.adapter.CommonAdapter;
import com.auto.learning.adapter.ViewHolder;
import com.auto.learning.bean.BookTypeBean;
import com.auto.learning.bean.ChooseBookBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.event.Handle;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.view.DragGridView;
import com.auto.learning.view.DragGridView.OnChanageListener;
import com.auto.learning.view.SharedPreferencesUtils;
import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ChooseBookPageFragment extends Fragment{
	
	private DragGridView gv_booklist;
	private ArrayList<BookTypeBean> bookTypeList = new ArrayList<BookTypeBean>();
	CommonAdapter adapter;
	private RelativeLayout rel_buttom,rel_top,rel_buttom2;
	private ImageView image_tips;
	private TextView tv_refresh;
	private final static int GET_LOCAL_BOOK_TYPE = 1;
	
	
	private Handle handle = new Handle(getActivity()){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				tv_refresh.setVisibility(View.GONE);
				bookTypeList.clear();
				ResponeResult result = (ResponeResult)msg.obj;
				ChooseBookBean	chooseBookBean = new Gson().fromJson(result.getData(), new TypeToken<ChooseBookBean>(){}.getType());
				if (chooseBookBean != null && chooseBookBean.getBookTypeList() != null) {
					bookTypeList.addAll(chooseBookBean.getBookTypeList());
				}
				Cache.addBookType(bookTypeList);
				if (adapter != null) {
					adapter.notifyDataSetChanged();
				}
				
				break;
			case HttpRequestHelper.GETDATA_FAIL:
				try {
					if(bookTypeList!=null&&bookTypeList.size()==0){
						tv_refresh.setVisibility(View.VISIBLE);
					}					CommonMethod.makeNotice(getActivity(), msg.obj.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case GET_LOCAL_BOOK_TYPE:
				bookTypeList.clear();
				if (msg.obj != null) {
					ArrayList<BookTypeBean> mTempList =	(ArrayList<BookTypeBean>) msg.obj;
					if (mTempList != null && mTempList.size() > 0) {
						bookTypeList.addAll(mTempList);
						if (adapter != null) {
							adapter.notifyDataSetChanged();
						}
					}
				}
				initData();
				break;
			case 2:
				Cache.addBookType(bookTypeList);
				break;
			}
		};
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View  view = inflater.inflate(R.layout.choosepage_fragment2 , null);
		initView(view);
		Cache.getAllBookType(handle);
		return view;
	}
	
	public void refreshUI(){
		initData();
	}
	
	private void initView(View  view){
		tv_refresh=(TextView) view.findViewById(R.id.tv_refresh);
		tv_refresh.setVisibility(View.GONE);
		tv_refresh.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				initData();	
			}
		});
		rel_buttom = (RelativeLayout) view.findViewById(R.id.rel_buttom);
		rel_buttom2 = (RelativeLayout) view.findViewById(R.id.rel_buttom2);
		rel_top = (RelativeLayout) view.findViewById(R.id.rel_top);
		rel_buttom.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				StatService.onEvent(getActivity(), "LogEventChoosePageClick", "阅读偏好设置点击");
				if (bookTypeList != null && bookTypeList.size() > 0) {
					if (adapter != null) {
						gv_booklist.setCanDrag(true);
						((MainActivity)getActivity()).setCanScroll(false);
					}
					rel_top.setVisibility(View.VISIBLE);
					rel_buttom2.setVisibility(View.VISIBLE);
					rel_buttom.setVisibility(View.INVISIBLE);
				}
			}
		});
		rel_buttom2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (adapter != null) {
					gv_booklist.setCanDrag(false);
					((MainActivity)getActivity()).setCanScroll(true);
				}
				rel_top.setVisibility(View.GONE);
				rel_buttom2.setVisibility(View.GONE);
				rel_buttom.setVisibility(View.VISIBLE);
				bookTypeSort();
			}
		});
		ImageView image_bg =  (ImageView) view.findViewById(R.id.image_bg);
		image_tips =  (ImageView) view.findViewById(R.id.image_tips);
		image_bg.setImageBitmap(CommonMethod.readBitMap(getActivity(), R.drawable.favoritebg));
		if ((boolean)SharedPreferencesUtils.getParam(getActivity(), "show_choose_book_tips_mm", true)) {
			image_tips.setVisibility(View.VISIBLE);
			image_tips.setImageBitmap(CommonMethod.readBitMap(getActivity(), R.drawable.choose_book_tips));
		}else {
			image_tips.setVisibility(View.GONE);
		}
		image_tips.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				image_tips.setVisibility(View.GONE);
				SharedPreferencesUtils.setParam(getActivity(), "show_choose_book_tips_mm", false);
			}
		});
		gv_booklist = (DragGridView) view.findViewById(R.id.gv_booklist);
		gv_booklist.setDragResponseMS(200);
		adapter = new CommonAdapter<BookTypeBean>(getActivity(), bookTypeList, R.layout.choose_book_item) {
			@Override
			public void convert(ViewHolder viewHolder, BookTypeBean item) {
				viewHolder.setText(R.id.tv_type_name, item.getTypeName()+"");
				ImageLoader.getInstance().displayImage(item.getFaceImg(), (ImageView)viewHolder.getView(R.id.image_book_face));
				ImageLoader.getInstance().displayImage(item.getFaceImg(), (ImageView)viewHolder.getView(R.id.image_book_face_shrap));
			}
		};
		gv_booklist.setAdapter(adapter);
		gv_booklist.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gv_booklist.setCanDrag(false);
		gv_booklist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (gv_booklist.isCanDrag()) {
					return;
				}
				Intent intent = new Intent(getActivity(), TopBookListActivity.class);
				intent.putExtra("type", "2");
				intent.putExtra("bean", bookTypeList.get(position));
				getActivity().startActivity(intent);
			}
		});
		gv_booklist.setOnChangeListener(new OnChanageListener() {
			
			@Override
			public void onChange(int from, int to) {
				BookTypeBean temp = bookTypeList.get(from);
				//这里的处理需要注意下
				if(from < to){
					for(int i=from; i<to; i++){
						Collections.swap(bookTypeList, i, i+1);
					}
				}else if(from > to){
					for(int i=from; i>to; i--){
						Collections.swap(bookTypeList, i, i-1);
					}
				}
				bookTypeList.set(to, temp);
				adapter.notifyDataSetChanged();
			}
		});
	}
	
	public void complateDrag(){
		if(gv_booklist != null ? gv_booklist.isCanDrag() : false){
			if (adapter != null) {
				gv_booklist.setCanDrag(false);
				((MainActivity)getActivity()).setCanScroll(true);
			}
			rel_top.setVisibility(View.GONE);
			rel_buttom2.setVisibility(View.GONE);
			rel_buttom.setVisibility(View.VISIBLE);
			bookTypeSort();
		}
	}
	
	
	private void initData(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(),HttpRequestHelper.USERID, 0))));
		HttpRequestHelper.executeHttpData(getActivity(), HttpRequestHelper.NATION_TYPE_LIST, params, handle, HttpRequestHelper.GETDATA_SUCCESS,HttpRequestHelper.GETDATA_FAIL);
	}
	
	/**
	 * 排序
	 */
	private void bookTypeSort(){
		StringBuilder builder = new StringBuilder("");
		if (bookTypeList != null && bookTypeList.size() > 0) {
			int size = bookTypeList.size();
			for (int i = 0; i < size; i++) {
				if (i== size - 1) {
					builder.append(bookTypeList.get(i).getTypeId()+"");
				}else {
					builder.append(bookTypeList.get(i).getTypeId()+",");
				}
			}
		}
		if (!TextUtils.isEmpty(builder.toString())) {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(),HttpRequestHelper.USERID, 0))));
			params.add(new BasicNameValuePair("typeIdList", String.valueOf(builder.toString())));
			HttpRequestHelper.executeHttpData(getActivity(), HttpRequestHelper.BOOK_TYPE_SORT, params, handle, 2, HttpRequestHelper.GETDATA_FAIL);
		}
	}
}
